package com.xmcowell.sportpacemaster.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ResolveInfo;
import android.util.Log;

import java.io.IOException;
import java.util.List;

/**
 * Created by Administrator on 2017/8/17 0017.
 */

public class ProcessUtil {

    public static void killProcessThread(final Context context){
        //清除进程
        new Thread(new Runnable() {
            @Override
            public void run() {
                String processName = PreferencesUtils.getValueFromSPMap(context, PreferencesUtils.Keys.PROCESS_NAME);
                Log.e("ProcessUtil", "进入第三方线程名称 processName = " + processName);

                if (processName == null || processName.equals(""))
                    return;
                ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
                List<ActivityManager.RunningAppProcessInfo> info = am.getRunningAppProcesses();
                for (ActivityManager.RunningAppProcessInfo item : info) {
                    ProcessUtil.killProcess(context, item, processName);
                }
            }
        }).start();
    }
    public static void killProcess(Context context, ActivityManager.RunningAppProcessInfo processInfo, String processName) {
        final int pid = processInfo.pid;
        if (processInfo.processName.equals(processName)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Runtime runtime = Runtime.getRuntime();
                    String cmd = "kill " + pid;
                    try {
                        Process exec = runtime.exec(cmd);
                        int result = exec.waitFor();
                        if (result == 0) {
                            Log.e("Kill Process", "success pid = " + pid);
                        }
                    } catch (IOException | InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}
